package com.chao.base.io.fileio;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.*;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.StandardCharsets;

/**
 * @author : Rookie
 * @description : 非阻塞IO是指在进行IO操作时，程序会立即返回，不会等待IO操作完成，
 * * 而是通过轮询等方式来判断IO操作是否完成。在Java中，非阻塞IO主要是通过Selector和Channel来实现的。
 * @date : 2023/6/13
 */
public class NioDemo {

    public static void main(String[] args) {
        write();
    }

    private static void read() {
        // 创建缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        InputStream is = null;
        try {
            is = NioDemo.class.getClassLoader().getResourceAsStream("test.txt");
            assert is != null;
            ReadableByteChannel channel = Channels.newChannel(is);
            // 从fileChannel中读取数据到缓冲区
            int bytesRead = channel.read(byteBuffer);
            while (bytesRead != -1) {
                // 将ByteBuffer切换为读模式
                byteBuffer.flip();
                // 使用 CharsetDecoder 将字节转换为字符
                CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder();
                CharBuffer charBuffer = decoder.decode(byteBuffer);
                System.out.print(charBuffer);
                // 清空缓冲区，为下一次读取操作做准备
                byteBuffer.clear();
                // 再次从fileChannel读取数据到缓冲区
                bytesRead = channel.read(byteBuffer);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void write() {
        ByteBuffer byteBuffer = ByteBuffer.wrap("hello,nio".getBytes(StandardCharsets.UTF_8));
        try (FileChannel channel = new FileOutputStream("nioTest.txt").getChannel()) {
            channel.write(byteBuffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
